package com.zhibi.util.itext;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.util.List;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.zhibi.util.reflect.ReflectUtil;

@SuppressWarnings("deprecation")
public class PdfUtil {

	private Document document;

	private static BaseFont bfChinese;
	private Font font;
	private String webid="zhibi";

	public String getWebid() {
		return webid;
	}

	public void setWebid(String webid) {
		this.webid = webid;
	}

	public PdfUtil(String path) {
		document = new Document();
		File file = new File(path);
		if(!file.getParentFile().exists()) {//判断父路劲是否存在
			file.getParentFile().mkdir();
		}
		try {
			PdfWriter.getInstance(document, new FileOutputStream(path,true));// 建立一个PdfWriter对象
			document.open();
			bfChinese = BaseFont.createFont("STSong-Light",
					"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 设置中文字体
			font = new Font(bfChinese, 10, Font.NORMAL);// 设置字体大小
		} catch (Exception de) {
			de.printStackTrace();
			throw new RuntimeException("生成pdf文件出错");
		} 
	}

	public int getPageNumber(){
		if(document==null){
			return 0;
		}
		return document.getPageNumber();
	}

	public static PdfUtil instance(String path) {
		return new PdfUtil(path);
	}

	/**
	 * 添加表格  
	 * @param data 数据
	 * @param cellWidth 单元格宽度  
	 * @param num 一共多少列
	 * @throws DocumentException
	 */
	public void addTable(List<List<String>> data, float cellWidth, int num)
			throws DocumentException {
		float[] widths =new float[num];
		for(int i=0;i<num;i++){
			widths[i] = cellWidth;
		}
		PdfPTable table = new PdfPTable(widths);// 建立一个pdf表格
		table.setSpacingBefore(10f);// 设置表格上面空白宽度
		table.setTotalWidth(cellWidth * num);// 设置表格的宽度
		table.setLockedWidth(true);// 设置表格的宽度固定

		PdfPCell cell = null;
		for (int i = 0; i < data.size(); i++) {
			for (String s : data.get(i)) {
				if(s == null){
					s = "--";
				}
				cell = new PdfPCell(new Paragraph(s, font));// 建立一个单元格
				table.addCell(cell);
			}
		}
		document.add(table);
	}

	/**
	 * 添加表格
	 * @param data
	 * @param titles
	 * @param fields
	 * @param clazz
	 * @param cellWidth
	 * @throws DocumentException
	 */
	public void addTable(List<?> data,String[] titles , String[] fields,Class<?> clazz,float cellWidth) throws DocumentException{
		float[] widths =new float[fields.length];
		for(int i=0;i<fields.length;i++){
			widths[i] = cellWidth;
		}
		PdfPTable table = new PdfPTable(widths);// 建立一个pdf表格
		table.setSpacingBefore(10f);// 设置表格上面空白宽度
		table.setTotalWidth(cellWidth * fields.length);// 设置表格的宽度
		table.setLockedWidth(true);// 设置表格的宽度固定

		PdfPCell cell = null;

		for(String title : titles){
			cell = new PdfPCell(new Paragraph(title, font));// 建立一个单元格
			table.addCell(cell);
		}

		//主要内容
		for(int i=0;i<data.size();i++){
			Object o=data.get(i);
			if(o==null){
				continue;
			}
			String value = null;
			for(int j=0;j<fields.length;j++){
				value=ReflectUtil.invokeGetMethod(clazz, o, fields[j]).toString();
				cell = new PdfPCell(new Paragraph(value, font));// 建立一个单元格
				table.addCell(cell);
			}
		}
		document.add(table);
	}

	public void addTable(PdfPTable table)
			throws DocumentException {
		document.add(table);
	}

	/**
	 * 添加标题 
	 * @param text
	 * @throws DocumentException
	 */
	public void addTitle(String text) throws DocumentException {
		font = new Font(bfChinese, 18, Font.BOLD);// 设置字体大小
		Paragraph p = new Paragraph(text, font);
		if(webid!=null){
			p.setAlignment(Element.ALIGN_CENTER);
			p.setIndentationLeft(Element.ALIGN_MIDDLE);
		}else{
			p.setAlignment(Element.ALIGN_CENTER);
		}
		document.add(p);
	}	


	/**
	 * 添加作者
	 * @param author
	 * @throws DocumentException
	 */
	public void addAuthor(String author) throws DocumentException{
		font = new Font(bfChinese, 14, Font.BOLD);// 设置字体大小
		Paragraph p = new Paragraph(author, font);
		p.setAlignment(Element.ALIGN_RIGHT);
		p.setSpacingAfter(20f);
		document.add(p);
	}


	/**
	 * 添加内容
	 * @param text
	 * @throws DocumentException
	 */
	public void addText(String text) throws DocumentException {
		font = new Font(bfChinese, 12, Font.BOLD);// 设置字体大小
		Paragraph p = new Paragraph(text, font);
		p.setSpacingAfter(10f);

		p.setAlignment(Element.ALIGN_LEFT);
		p.setIndentationLeft(1f);
		document.add(p);
	}

	/**
	 * 添加html
	 * @param html
	 * @throws Exception
	 */
	public void addHtml(String html) throws Exception {
		StyleSheet st = new StyleSheet();
		List<?> list = HTMLWorker.parseToList(new StringReader(html), st);
		for (int k = 0; k < list.size(); ++k) {
			document.add((Element) list.get(k));
		}
	}

	/**
	 * 生成pdf文件
	 */
	public void exportPdf() {
		document.close();
	}

	/**
	 * 添加水印
	 * @param inPdfFile
	 * @param outPdfFile
	 * @param markImagePath
	 * @param waterMarkName
	 * @throws Exception
	 */
	public static void addPdfMark(String inPdfFile, String outPdfFile,
			String markImagePath,String waterMarkName) throws Exception {
		try {  
            PdfReader reader = new PdfReader(inPdfFile);  
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(  
            		outPdfFile));  
  
            int total = reader.getNumberOfPages() + 1;  
            Image image = Image.getInstance(markImagePath);  
  
            // 图片位置  
            image.setAbsolutePosition(200, 480);  
            PdfContentByte under;  
            int j = waterMarkName.length();  
            char c = 0;  
            int rise = 0;  
            for (int i = 1; i < total; i++) {  
                rise = 400;  
                under = stamper.getUnderContent(i);  
                under.beginText();  
                under.setFontAndSize(bfChinese, 30);  
  
                if (j >= 15) {  
                    under.setTextMatrix(200, 120);  
                    for (int k = 0; k < j; k++) {  
                        under.setTextRise(rise);  
                        c = waterMarkName.charAt(k);  
                        under.showText(c + "");  
                    }  
                } else {  
                    under.setTextMatrix(240, 100);  
                    for (int k = 0; k < j; k++) {  
                        under.setTextRise(rise);  
                        c = waterMarkName.charAt(k);  
                        under.showText(c + "");  
                        rise -= 18;  
  
                    }  
                }  
                // 添加水印文字  
                under.endText();  
                // 添加水印图片  
                under.addImage(image);   
                under.setLineWidth(1f);  
                under.stroke();  
            }  
            stamper.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
	}

	/**
	 * 插入图片
	 * @param image
	 */
	public  void addImage(Image image){
		try {
			image.setAlignment(Image.UNDERLYING);
			image.scaleAbsolute(70.0f, 70.0f);
			document.add(image);
		} catch (BadElementException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加多张图片
	 * @param images
	 */
	public void addImages(List<Image> images){
		try {
			for(Image image:images){
				image.setAlignment(Image.ALIGN_CENTER);
				image.scaleAbsolute(700.0f, 700.0f);
				document.add(image);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addHtmlList(List<Element> list) throws DocumentException {
		for(Element e:list){
			document.add(e);
		}
	}

	public Font getFont() {
		return font;
	}

	public void setFont(Font font) {
		this.font = font;
	}

}
